/**
 * 封装sendRequest请求
 * @param {Object} url	请求路径
 * @param {Object} data	请求参数	
 * @param {Object} method	请求方法默认为POST
 * @param {Object} options	 RequestOptions
 */
import config from './config.js'
const SendUrl = config.Url

// 添加拦截器
const httpInterceptor = {
	// 拦截前触发
	invoke(options) {
		options.header = {
			'source': '1',
			'content-type': "application/json;charset=UTF-8",
			...options.header,

		}
		const access_token = uni.getStorageSync("b-token") || 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3MjE1NTI2NTIsImlhdCI6MTcyMDk0Nzg1MiwidXNlcklkIjoxNzYyNzE4MTAzNTU0MjMyMzIwfQ.pXseIKH5Sc24irkRG9XJy7hb8HZjiI-Y3AKH1xjM-RM'
		if (access_token) {
			options.header.authorization = access_token
		}
	},
}
uni.addInterceptor('request', httpInterceptor)
const sendRequest = (url, param = {}, method = "POST", options = {}, isShowToast = true) => {
	return new Promise(function (resolve, reject) {
		uni.request({
			url: SendUrl + url,
			data: param,
			method: method,
			success: (res) => {
				if (res.data.code == 200 || res.data.code == 0) {
					resolve(res);
				} else {
					if (isShowToast) {
						uni.showToast({
							title: res.data.msg,
							mask: true,
							icon: "none",
							duration: 1000
						})
					}
					resolve(res);
				}
			},
			fail: (err) => {
				reject(err)
				console.error(err)
			},
			complete() {

			},
			...options
		})
	}).catch((e)=>{});

}

const post = (url, param = {}, options = {}) => {
	return new Promise((resolve, reject) => {
		sendRequest(url, param, "POST", options).then(res => {
			resolve(res.data.data);
		}).catch(err => {
			reject(err);
		});
	});
}

const get = (url, param = {}, options = {}) => {
	return new Promise((resolve, reject) => {
		sendRequest(url, param, "GET", options).then(res => {
			resolve(res.data.data);
		}).catch(err => {
			reject(err);
		});
	});
}
export default {
	sendRequest,
	post,
	get
}